import os
from utils import extract_docx_text, extract_docx_text_enhanced, extract_doc_text, extract_doc_text_enhanced, extract_text_fallback, clean_text, save_as_jsonl, save_as_txt

class DocConverter:
    def __init__(self, log_callback=None):
        self.log_callback = log_callback
        self.is_converting = False
        
    def log(self, message):
        if self.log_callback:
            self.log_callback(message)
            
    def convert_documents(self, input_dir, output_dir, output_format="jsonl", min_length=5, remove_empty=True):
        self.is_converting = True
        
        self.log(f"开始转换: {input_dir}")
        
        # 获取所有DOC/DOCX文件
        doc_files = []
        for root, _, files in os.walk(input_dir):
            for file in files:
                if file.endswith(('.doc', '.docx')):
                    doc_files.append(os.path.join(root, file))
        
        total_files = len(doc_files)
        self.log(f"找到 {total_files} 个文档文件")
        
        if total_files == 0:
            self.log("未找到任何DOC/DOCX文件")
            self.is_converting = False
            return False, "未找到任何DOC/DOCX文件"
            
        # 创建输出目录
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
            
        # 处理每个文件
        processed_count = 0
        for file_path in doc_files:
            if not self.is_converting:
                break
                
            try:
                self.log(f"处理文件: {os.path.basename(file_path)}")
                self.process_document(file_path, output_dir, output_format, min_length, remove_empty)
                processed_count += 1
            except Exception as e:
                self.log(f"处理文件 {file_path} 时出错: {str(e)}")
        
        success = processed_count > 0
        message = f"转换完成: 成功处理 {processed_count}/{total_files} 个文件"
        self.log(message)
        self.is_converting = False
        
        return success, message
        
    def process_document(self, file_path, output_dir, output_format, min_length, remove_empty):
        filename = os.path.basename(file_path)
        name_without_ext = os.path.splitext(filename)[0]
        
        # 验证文件是否存在
        if not os.path.exists(file_path):
            self.log(f"错误: 文件不存在 - {file_path}")
            return
            
        # 验证文件是否可读
        if not os.access(file_path, os.R_OK):
            self.log(f"错误: 无法读取文件 - {file_path}")
            return
        
        # 提取文本
        try:
            if file_path.endswith('.docx'):
                text = extract_docx_text_enhanced(file_path)
                self.log(f"从DOCX提取文本成功: {filename}")
            else:  # .doc
                text = extract_doc_text_enhanced(file_path)
                self.log(f"从DOC提取文本成功: {filename}")
                
            # 记录提取的文本长度
            text_length = len(text)
            self.log(f"提取的文本长度: {text_length} 字符")
            
            # 清理文本
            cleaned_text = clean_text(text, remove_empty, min_length)
            self.log(f"清理后文本行数: {len(cleaned_text)}")
            
            # 如果没有提取到文本，尝试备用方法
            if not cleaned_text:
                self.log(f"警告: 未提取到文本，尝试备用方法: {filename}")
                fallback_text = extract_text_fallback(file_path)
                if fallback_text.strip():
                    cleaned_text = clean_text(fallback_text, remove_empty, min_length)
                    self.log(f"备用方法提取的文本行数: {len(cleaned_text)}")
            
            # 保存结果
            if cleaned_text:
                if output_format == 'jsonl':
                    output_path = os.path.join(output_dir, f"{name_without_ext}.jsonl")
                    save_as_jsonl(cleaned_text, output_path)
                else:  # txt
                    output_path = os.path.join(output_dir, f"{name_without_ext}.txt")
                    save_as_txt(cleaned_text, output_path)
                self.log(f"成功保存: {filename}")
            else:
                self.log(f"警告: 未提取到可用的文本内容: {filename}")
                
        except Exception as e:
            self.log(f"处理文件 {filename} 时出错: {str(e)}")
            # 尝试使用备用方法
            try:
                self.log(f"尝试备用方法处理: {filename}")
                fallback_text = extract_text_fallback(file_path)
                if fallback_text.strip():
                    cleaned_text = clean_text(fallback_text, remove_empty, min_length)
                    if cleaned_text:
                        if output_format == 'jsonl':
                            output_path = os.path.join(output_dir, f"{name_without_ext}.jsonl")
                            save_as_jsonl(cleaned_text, output_path)
                        else:  # txt
                            output_path = os.path.join(output_dir, f"{name_without_ext}.txt")
                            save_as_txt(cleaned_text, output_path)
                        self.log(f"备用方法处理成功: {filename}")
            except Exception as fallback_error:
                self.log(f"备用方法也失败: {str(fallback_error)}")
            
    def stop_conversion(self):
        self.is_converting = False
        self.log("转换已停止")

